package cn.edu.swufe.surverpark.struts2.action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.edu.swufe.surverpark.model.Answer;
import cn.edu.swufe.surverpark.model.Question;
import cn.edu.swufe.surverpark.model.Survey;
import cn.edu.swufe.surverpark.struts2.service.SurveyService;

/**
 *@author 陈龙 E-mail:529914446@qq.com
 *@version创建时间:2015年5月5日上午6:12:17
 *类说明
 */
@Controller
@Scope("prototype")
public class CollectionSurveyAction extends BaseAction<Survey> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5392295339769450949L;
	
	private Integer sid;
	private InputStream is;
	@Resource
	private SurveyService surveyService;
	public Integer getSid() {
		return sid;
	}

	public void setSid(Integer sid) {
		this.sid = sid;
	}
	public String execute(){
		return SUCCESS;
	}
	public InputStream getIs(){
		System.out.println("开始");
		try{
			Map<Integer,Integer> qidIndexMap = new HashMap<Integer,Integer>();
			List<Question> list = surveyService.getQuestions(sid);
			HSSFWorkbook wb = new HSSFWorkbook();
			HSSFSheet sheet = wb.createSheet("收集调查");
			HSSFRow row = sheet.createRow(0);
			HSSFCell cell = null;
			Question q = null;
			for(int i=0;i<list.size();i++){
				q = list.get(i);
				cell = row.createCell(i);
				cell.setCellValue(q.getTitle());
				sheet.setColumnWidth(i,6000);
				qidIndexMap.put(q.getId(),i);
			}
			HSSFCellStyle style = wb.createCellStyle();
			style.setWrapText(true);
			List<Answer> answers = surveyService.getAnswers(sid);
			String oldUuid = "";
			int rowIndex = 0;
			for(Answer a : answers){
				if(!oldUuid.equals(a.getUuid())){
					rowIndex ++;
					oldUuid = a.getUuid();
					row = sheet.createRow(rowIndex);
				}
				cell = row.createCell(qidIndexMap.get(a.getQuestionId()));
				cell.setCellValue(a.getAnswerIds());
				cell.setCellStyle(style);
			}
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			wb.write(baos);
			return new ByteArrayInputStream(baos.toByteArray());
			
		} catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
}

